var express = require("express");
var router = express.Router();
var User = require("../models/user.js");

router.get("/", function (req, res, next) {
	res.render("login.jade");
});

router.post("/", function (req, res, next) {
	var data = "";
	req.setEncoding("utf8");
	req.on("data", function (chunk) {
		data += chunk;
	});
	req.on("end", function () {
		var json = {};
		try {
			json = JSON.parse(data);
		}
		catch (err) {
			res.status(400).send("ParseError");
			return;
		}
		if (json.userName && json.password) {
			User.signIn(json.userName, json.password).then(function (value) {
				res.sendStatus(200);
			}, function (err) {
				if (err === undefined) // 密码不正确
					res.status(403).send("PasswordError");
				else if (err === User.userNotExistedError)
					res.status(403).send("UserNotExistedError");
				else if (err instanceof RangeError) // 用户名或密码不符合要求
					res.status(400).send("RangeError");
				else
					res.sendStatus(500);
			});
		}
	});
});

module.exports = router;